package utils

import (
	"errors"
	"fmt"
	"gitee.com/jack_zang/public-scripts/go/elastic-ops/global"
	elastic "github.com/elastic/go-elasticsearch/v8"
)

func GetEsClient() (client *elastic.Client, err error) {
	elasticsearchURL := "http://" + global.AswConfig.Es.Addr

	cfg := elastic.Config{
		Addresses: []string{
			elasticsearchURL,
		},
		APIKey: global.AswConfig.Es.ApiToken, // Use API token for authentication
	}

	// Create a new Elasticsearch client
	client, err = elastic.NewClient(cfg)
	if err != nil {
		global.AswLog.Error("初始化 Es Client 失败")
		return nil, errors.New("初始化 Es Client 失败")
	}
	return client, err
}

func EsDelIndex(indexName string) (msg string, err error) {
	client, err := GetEsClient()
	if err != nil {
		return "", err
	}

	// Delete the index
	resp, err := client.Indices.Delete([]string{indexName})
	if err != nil {
		return "", err
	}
	fmt.Println("----resp:", resp.StatusCode)
	return resp.String(), err
	//defer resp.Body.Close()

	//if resp.IsError() {
	//	log.Fatalf("Error deleting index: %s", resp.Status())
	//}
	//
	//fmt.Printf("Index '%s' deleted successfully.\n", indexName)
}
